/*!
 @header DynamicViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/24 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */    

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：动态商讯，显示用户所有的动态；动态分为三种：心情动态、推荐动态和商品动态
//  naviBar上左边为圈子管理按钮，中间为圈子内动态过滤功能，右边为发布商讯
//
//  动态内容，一个动态的head处为发布此动态的发布者的简易信息，并且点击会进入此人的个人详情页；
//
//  head下面是此动态的文字描述部分，此部分的高度需要根据用户输入的内容动态设置高度；
//      当为商品动态时，此部分显示为商品信息；
//
//  文字描述部分下面是图片部分，填充时，要判断是否有图片。如果无图片就将高度设为0；
//      当为推荐动态时，此部分特殊，是以UIImageView为背景，里面填充的是商品信息和商品图片；
//
//      图片最多为三张，如果没有图片那么就隐藏；
//
//      这部分需要根据内容动态设置高度。
//
//  图片部分下面是footview部分，当此动态为心情时，那么footview中只有评论数；当动态为推荐动态和
//      商品动态时，那么footview中评论数、交易数和推荐数都有。
//
//  <功能描述>：CashRecordsViewController功能较为简单，实现刷新基类的代理方法，就可以实现上拉和加载更多的功能。
//  	<实现描述>：下拉：应重写并调用BaseRefreshViewController的reloadTableViewDataSource方法，在方法中实现自己的刷新数据源的方法。
//                加载更多：应重写并调用BaseRefreshViewController的refreshButtonEvent:方法，触发加载更多按钮事件。
//      <注意事项>：1、刷新时机，即_reloading，已经启动刷新时应将_reloading设为YES，防止刷新重复进行，刷新结束应将_reloading设为NO，准备下次刷新。
//                2、_isFooterRefresh，用于判断是否是加载更多，便于需要同时用到下拉和加载更多的地方判断如何刷新数据源。
//                《更多实现详见BaseRefreshViewController.m》
//
//  <功能描述>：圈子过滤，用户点击popover上的圈子名称，每点击一次就向服务器发送一次带有此圈子id的请求，过滤出此圈子内的动态。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述                                                 版本
//
//  周益    2013-5-6       限制title的长度，最多只能显示4个字，多出的字显示"..."          1.0.1

#import "DynamicViewController.h"
#import "Helper.h"
#import "Config.h"
//#import "CircleListViewController.h"
#import "MoodFormViewController.h"
#import "FPPopoverController.h"
#import "DynamicDetailViewController.h"
#import "PersonalViewController.h"
#import "JMFBase.h"
#import <QuartzCore/QuartzCore.h>
#import "CellFactory.h"
#import "AnnouncementViewController.h"
#import "Announcement.h"
#import "DBKit.h"
#import "FPTouchView.h"
#import "ACNavBarDrawer.h"
#import "ShoppingViewController.h"
#import "CircleHomeViewController.h"
#import "RelationConfirmationViewController.h"
#import "MJRefresh.h"

@interface DynamicViewController ()<ACNavBarDrawerDelegate, MJRefreshBaseViewDelegate>
{
    FPTouchView *_touchView;
    
    /** 是否已打开抽屉 */
    BOOL _isOpen;
    
    /** 抽屉视图 */
    ACNavBarDrawer *_drawerView;
    
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

@end

@implementation DynamicViewController
@synthesize times = _times;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundView = nil;
    
//    self.title = _L(@"vc_title_038");
    
    //左按钮：管理圈子
    UIButton* circleManagementButton = [Helper buttonWithStyle:ButtonStyleNavigationCircleList];
    [circleManagementButton addTarget:self action:@selector(circleManagementButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:circleManagementButton];
    
    
    //右按钮：添加商讯
    UIButton* writeMessageButton = [Helper buttonWithStyle:ButtonStyleNavigationWriteMessage];
    [writeMessageButton addTarget:self action:@selector(writeMessageButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:writeMessageButton];
    
    //在导航栏中，插入一个自定义视图，用于接受用户点击事件，并绘制一个向下的箭头
    
    _navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
    [_navButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = _navButton;
    //向服务器发送获取圈子动态请求，并接受动态消息
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(35.0f, 0.0f, 115.0f, 44.0f)];
    _titleLabel.font = _SYS_FONT_009;
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.shadowColor = nil;
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.text = _L(@"vc_title_038");
    
    CGSize size = [_titleLabel.text sizeWithFont:_SYS_FONT_009 constrainedToSize:CGSizeMake(115.0f, 44.0) lineBreakMode:NSLineBreakByCharWrapping];
    _titleLabel.frame = CGRectMake(35.0f, 0.0f, size.width, 44.0f);
    [_navButton addSubview:_titleLabel];
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_titleLabel.frame.origin.x + _titleLabel.frame.size.width + 1.0f, 20.0f, 15.0f, 8.0f)];
    _imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_001@2x" ofType:@"png"]];
    [_navButton addSubview:_imageView];
    
    [self circleMessageRequest];
    
    _announcementView = [[ASImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 50.5f)];
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(announcementViewEvent:)];
    [_announcementView.imageView addGestureRecognizer:gestureRecognizer];
    
    _deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 50.5f, 50.5f)];
    
    [_deleteButton setImage:[UIImage imageNamed:@"com_btn_027_n"] forState:UIControlStateNormal];
    [_deleteButton addTarget:self action:@selector(deleteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_announcementView addSubview:_deleteButton];
    
    //创建弹出菜单栏
    NSArray *item_01 = [NSArray arrayWithObjects:@"com_btn_032_n@2x", _L(@"btn_title_01"), nil];
    NSArray *item_02 = [NSArray arrayWithObjects:@"com_btn_033_n@2x", _L(@"btn_title_02"), nil];
    
    NSArray *allItems = [NSArray arrayWithObjects:item_01,item_02, nil];
    
    _drawerView = [[ACNavBarDrawer alloc] initWithView:self.view andItemInfoArray:allItems];
    _drawerView.delegate = self;
    _drawerView.hidden = YES;
    
    _messageArray = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
    
}

//- (void)viewDidAppear:(BOOL)animated
//{
////    [self.navigationController.navigationBar insertSubview:_navButton atIndex:99];
//    
//}
//
//- (void)viewWillDisappear:(BOOL)animated
//{
////    [_navButton removeFromSuperview];
//
//}
//页面将要进入前台，开启定时器
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //开启定时器
    [_timer setFireDate:[NSDate distantPast]];
    [_announcementTimer setFireDate:[NSDate distantPast]];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    //关闭定时器
    [_timer setFireDate:[NSDate distantFuture]];
    [_announcementTimer setFireDate:[NSDate distantFuture]];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return _messageArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //获取一条动态信息
    NSDictionary* dynamic = [_messageArray objectAtIndex:indexPath.section];
    
    #warning: 这里要优化，使用静态的形式
    NSArray* Cellidentifiers = [NSArray arrayWithObjects:@"Cell_Info", @"Cell_Mood", @"Cell_Goods", @"Cell_Recommend", nil];
    UITableViewCell *cell;
    
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:0]];
        if (cell == nil) {
            //获取复用对象
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:0]];
            [CellFactory makeCell:cell forName:NamedCellPersonInformation];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:NamedCellPersonInformation withDictionary:dynamic];
    }
    
    else {
        NSInteger type = [[dynamic objectForKey:@"type"] integerValue];
        NSInteger cellType = type;
        //使用Light类，使界面变得短一些
        if (type == DynamicCategoryProduct) {
            type = 6;
        }
        else if (type == DynamicCategoryRecommend) {
            type = 7;
        }
        else if (type == DynamicCategoryMood) {
            type = 5;
        }
        
        //根据不同的动态类型，获取队列中的不同复用对象
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:cellType]];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:cellType]];
            [CellFactory makeCell:cell forName:type];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:type withDictionary:dynamic];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 0.0f;
    
    NSDictionary *dynamic = [_messageArray objectAtIndex:indexPath.section];

    if (indexPath.row == 1) {
        
        NSInteger type = [[dynamic objectForKey:@"type"] intValue];
        //如果type是产品/推荐信息就是用Light类，使界面变得短一些
        if (type == DynamicCategoryProduct) {
            type = 6;
        }
        else if (type == DynamicCategoryRecommend) {
            type = 7;
        }
        else if (type == DynamicCategoryMood) {
            type = 5;
        }
        height = [CellFactory heightForName:type withDictionary:dynamic];
    }
    else {
        height = [CellFactory heightForName:NamedCellPersonInformation withDictionary:dynamic];
    }
    
    return height;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //获得被用户选中的动态
    NSDictionary *dynamicIsSelected = [_messageArray objectAtIndex:[indexPath section]];

    //如果用户点击的是个人简洁信息栏，那么就跳转到动态发起人的个人信息页面
    if (indexPath.row == 0) {
        
        //获取动态发起人的personid
        NSInteger psersonId = [[dynamicIsSelected objectForKey:@"creatorId"] integerValue];
        
        //跳转到个人信息页面
        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:psersonId];
        personalInfoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personalInfoVC animated:YES];
        
    }else{
        
        NSInteger dynamicId = [[dynamicIsSelected objectForKey:@"id"] integerValue];
        
        DynamicDetailViewController *trendDetailVC = [[DynamicDetailViewController alloc] initWithID:dynamicId];
        trendDetailVC.hidesBottomBarWhenPushed = YES;
        trendDetailVC.operateDelegate = self;
        [self.navigationController pushViewController:trendDetailVC animated:YES];
    }

}

#pragma mark - 私有方法

/*!
 @abstract 向服务器请求指定页数的圈子动态
 @discussion 用于用户点击toolbar时，根据badgevalue请求消息通知
 @param pageSize 消息数
 */
- (void)circleMessageRequestWithPageSize:(NSInteger)pageSize
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_MIME_LIST];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    request.requestMode = RequestModeMultiPart;
    [request setValue:[NSString stringWithFormat:@"%i", pageSize] forParameter:@"pageSize"];
    if (_currentCircleId != 0) {
        [request setValue:[NSString stringWithFormat:@"%i", _currentCircleId] forParameter:@"circleId"];
    }
    [request asynchronous];
}

/*!
 @abstract 向服务器请求指定圈子的圈子动态。
 @discussion 用户点击了popover中的圈子名称后会过滤圈子动态。
 */
- (void)circleMessageRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_MIME_LIST];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    request.requestMode = RequestModeMultiPart;
    
    if (_currentCircleId != 0) {
        [request setValue:[NSString stringWithFormat:@"%i", _currentCircleId] forParameter:@"circleId"];
    }

    [request asynchronous];
}

/*!
 @abstract 通过checkid查询向服务器请求更多的动态
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)circleMessageRequestWithCheckId:(NSString *)checkId
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_MIME_LIST];
    request.delegate = self;
    request.requestMode = RequestModeMultiPart;
    
    //checkId存在，则表明是加载更多
    if (checkId != nil) {
        
        [request setValue:checkId forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreMessageDidReceived:)];
    }
    
    //当前圈子
    if (_currentCircleId != 0) {
        
        [request setValue:[NSString stringWithFormat:@"%i", _currentCircleId] forParameter:@"circleId"];
    }
    
    [request asynchronous];
}

/*!
 @abstract 向服务器请求指定圈子的圈子动态。
 @discussion 用户点击了popover中的圈子名称后会过滤圈子动态。
 @param circleID 圈子id
 */
- (void)filterCircleMessageRequestByCircleID:(NSInteger)circleID
{
    _currentCircleId = circleID;

    [self circleMessageRequest];

}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (long)catchTheLastDataSourceId
{
    //获取数据源最后一项对象的id属性
    return [[[_messageArray objectAtIndex:(_messageArray.count - 1)] objectForKey:@"id"] longValue];
}

- (void)announcementRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_ANNOUNCEMENT_LIST];
    request.delegate = self;

    [request setValue:[NSString stringWithFormat:@"%d", 5] forParameter:@"pageSize"];
    
    request.successSelector = @selector(announcementDidReceived:);
    
    [request asynchronous];
}

- (void)findAnnouncements
{
    //从数据库取出所有的公告
    //此处的公告都是status=1的
    _announcementArray = [[DBKit sharedDBKit] getAnnouncementsFromDB];
}

- (void)showAnnoucementView
{

    //每一次都要对_times操作后，都要进行是否越界的判断，越界后就从0开始
    //越界后就循环
    if (_times <= 0 || _times >= _announcementArray.count) {
        
        _times = 0;
        
    }
    
    NSDictionary *announcement = _announcementArray[_times];
    
    if (announcement == nil) {
        return;
    }
    
    [_announcementView setImageURL:[NSURL URLWithString:announcement[@"imgUrlIos"]] andSourceImageURL:nil forStyle:PictureStyleAnnouncement];

    _announcementUrl = announcement[@"contentUrl"];
    
    _deleteButton.tag = [announcement[@"id"] integerValue];
    
    _announcementTitle = announcement[@"title"];
    //索引叠加
    _times += 1;

}

- (void)hideAnnoucementView
{
//    _announcementView = nil;
//    _deleteButton = nil;
    self.tableView.tableHeaderView = nil;
    
}

- (void)initTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval: 5.0f
                                              target:self
                                            selector: @selector(handleTimer:)
                                            userInfo:nil
                                             repeats:YES];
}

- (void)handleTimer:(NSTimer *)theTimer
{
    
    //显示一个公告
    [self showAnnoucementView];
    
}

- (void)startAnnouncementTimer
{
    _announcementTimer = [NSTimer scheduledTimerWithTimeInterval: 3600.0f
                                                          target:self
                                                        selector: @selector(handleAnnouncementTimer:)
                                                        userInfo:nil
                                                         repeats:YES];
}

- (void)handleAnnouncementTimer:(NSTimer *)theTimer
{
    
    //每一个小时就要想服务器请求一次公告
    [self announcementRequest];
}

/*!
 @abstract 在点击了导航栏的右按钮后，弹出的菜单栏消失时，必须调用此方法，隐藏菜单栏和让视图重新可以滚动
 */
- (void)recoverViewStatus
{
    _drawerView.hidden = YES;
    self.tableView.scrollEnabled = YES;
}

- (void)shoppingEnableRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_SHOPPING_CHECK];
    request.delegate = self;
    
    //此请求不加token参数
    [request setValue:@"" forParameter:@"token"];
    [request setSuccessSelector:@selector(shoppingEnableResponseDidReceived:)];
    [request asynchronous];
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - CircleInPopoverViewController Delegate

- (void)reloadCircleDataIByID:(NSDictionary *)circle
{
    _currentCircleId = [[circle objectForKey:@"id"] integerValue];
    
    //将popover抹去
    [_popover dismissPopoverAnimated:YES];
    
    NSInteger circleId;
    
    if (circle == nil) {

        _titleLabel.text = _L(@"vc_title_038");
        
        circleId = 0;
        
    }else{
        
        NSString *result = [NSString stringWithFormat:_L(@"tpl_04"), [circle objectForKey:@"name"]];  //%@圈子
        _titleLabel.text = result;
        
        circleId = [[circle objectForKey:@"id"] integerValue];
    }

    CGSize size = [_titleLabel.text sizeWithFont:_SYS_FONT_009 constrainedToSize:CGSizeMake(115.0f, 44.0) lineBreakMode:NSLineBreakByCharWrapping];
    _titleLabel.frame = CGRectMake(35.0f, 0.0f, size.width, 44.0f);
    CGFloat inset = 0;
    
    if (size.width > 90.0f) {
        
        inset = 5.0f;
        
        _titleLabel.frame = CGRectMake(35.0f - inset, 0.0f, size.width, 44.0f);
        
    }else if(size.width < 80.0f){
        
        inset = 10.0f;
        
        _titleLabel.frame = CGRectMake(35.0f + inset, 0.0f, size.width, 44.0f);
    }
    _imageView.frame = CGRectMake(_titleLabel.frame.origin.x + _titleLabel.frame.size.width, 20.0f, 15.0f, 8.0f);
    

    //发送过滤请求
    [self filterCircleMessageRequestByCircleID:circleId];
}


#pragma mark - JSONRequest Delegate
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {

        [self.navigationController.tabBarItem setBadgeValue:nil];
        
        if (_messageArray.count != 0) {
            [_messageArray removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            _footer.scrollView = self.tableView;
            
            NSMutableArray* filteredUnsaleProducts = [[NSMutableArray alloc] init];
            for (NSDictionary* dynamic in jmf.data) {
                
                //如果产品状态正常，没有停售或下架，就保存
                if (([dynamic[@"product"][@"status"] intValue] == 0)) {
                    
                    [filteredUnsaleProducts addObject:dynamic];
                }
            }
            
            //将保存好的数组载入
            [_messageArray addObjectsFromArray:filteredUnsaleProducts];
        }
        
        if (_messageArray.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
        
        //下拉刷新的时候，就要请求一次公告
        [self announcementRequest];
        
        //开始每一小时一次的公告请求
        [self startAnnouncementTimer];
        
        
        
//        
//        //当为下拉刷新和初次进入时，应该对数据源进行格式化
//        if (!_isFooterRefresh) {
//            
//            if (_messageArray == nil) {
//                _messageArray = [[NSMutableArray alloc] init];
//                
//            }else{
//                
//                [_messageArray removeAllObjects];
//            }
//            
//            //下拉刷新后将badgevalue清零
//            [self.navigationController.tabBarItem setBadgeValue:nil];
//            
//            
//        }
//        
//        //加载更多后成功获取数据后，应先调用此方法，恢复到点击加载更多之前的页面状态
//        [super stopRefresh];
//        
//        //如果加载更多没有得到数据，那么就提示用户，并且暂时隐藏家在更多
//        //在有数据的情况，就添加到数据源
//        if ([(NSArray *)jmf.data count] == 0) {
//            
//            //如果是加载更多时出现空数据源，那么就提示用户
//            if (_isFooterRefresh) {
//                [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//            }
//            
//            self.disableBottomRefresh = YES;
//            
//        }
//        //有数据情况下，对数据进行一次过滤，只显示商品没有下架或没有停售的
//        else{
//            
//            //有数据的时候，加载更多要显示出来
//            self.disableBottomRefresh = NO;
//            
//            
//        }        
//        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
}

- (void)moreMessageDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            NSMutableArray* filteredUnsaleProducts = [[NSMutableArray alloc] init];
            for (NSDictionary* dynamic in jmf.data) {
                
                //如果产品状态正常，没有停售或下架，就保存
                if (([dynamic[@"product"][@"status"] intValue] == 0)) {
                    
                    [filteredUnsaleProducts addObject:dynamic];
                }
            }
            
            //将保存好的数组载入
            [_messageArray addObjectsFromArray:filteredUnsaleProducts];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)announcementDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        
        [_timer invalidate];
        
        if (jmf.data.count == 0) {
            return;
        }
        
        if (_announcementArray == nil) {
            _announcementArray = [[NSMutableArray alloc] init];
        }
        else{
            
            [_announcementArray removeAllObjects];
        }
        
        [_announcementArray addObjectsFromArray:(NSArray *)jmf.data];
        
        //此处得到的数据源要和数据库中已被用户删除的公告做对比，剔除被删除的
        DBKit *dbkit = [DBKit sharedDBKit];
        NSMutableArray *announcementDeletedArray = [dbkit getAnnouncementsFromDB];
    
        //待删除的公告数组
        NSMutableArray *deletingArray = [[NSMutableArray alloc] init];
        
        //获取新一轮公告集合中，待删除的数组
        for (int i = 0; i < _announcementArray.count; i++) {
            
            NSDictionary *announcement_new = _announcementArray[i];
            
            for (int j = 0; j < announcementDeletedArray.count; j++) {
                
                Announcement *announcement_deleted = announcementDeletedArray[j];
                
                if ([announcement_new[@"id"] integerValue] == announcement_deleted.announcementId) {
                    
                    
                    [deletingArray addObject:announcement_new];
                    break;
                }
                
            }
        }
        
        //待删除的公告数组不为空，就要进行删除操作
        if (deletingArray.count != 0) {
            [_announcementArray removeObjectsInArray:deletingArray];
        }
        
        //存在公告就马上显示第一个公告，并且当公告大于1时，设置下一个在定时器中要显示的公告索引
        if (_announcementArray.count != 0) {
            
            //此处添加公告栏的代码一定要在这里，不能放在定时器的方法里面，否则定时器执行一次，_announcementView都会赋值给
            //headerView，就会引起tableview的contentSize的高度发生改变。所以符合逻辑的做法就是当存在公告的时候才显示出
            //headerview。
            if (self.tableView.tableHeaderView == nil) {
                
                self.tableView.tableHeaderView = _announcementView;
            }
            
            //立即显示第一个公告
            [self showAnnoucementView];
            
            //当公告数大于1的时候才开启定时器，并且设置图片设置从索引为1的公告开始
            if (_announcementArray.count > 1) {
                
                _times = 1;
                
                [self initTimer];
            }
            
        }
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


- (void)shoppingEnableResponseDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    //status为1 表示该切片开通了逛一逛
    //status为5 表示该切片未开通逛一逛
    if (jmf.status == JMStatusSucceed) {
        
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"shoppingEnable"];
//        if (!SHOPPING_ENABLE) {
//            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_125")];
//            return;
//        }
        
        ShoppingViewController *shoppingVC = [[ShoppingViewController alloc] initWithStyle:UITableViewStyleGrouped];
        shoppingVC.title = _L(@"btn_title_02");
        shoppingVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:shoppingVC animated:YES];
    }

    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


#pragma mark - 自定义事件


/*!
 @abstract 圈子管理事件
 */
- (void)circleManagementButtonEvent
{
    //隐藏下拉菜单的视图
    NSArray* views = self.navigationController.navigationBar.subviews;
    for (int i = 0; i < views.count; i++) {
        UIView* view = [views objectAtIndex:i];
        if (view.tag == 99) {
            [view setHidden:true];
        }
    }

    CircleHomeViewController *circleHomeVC = [CircleHomeViewController new];
    circleHomeVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:circleHomeVC animated:YES];
//    RelationConfirmationViewController *r = [[RelationConfirmationViewController alloc] init];
//    [self.navigationController pushViewController:r animated:YES];
}

/*!
 @abstract 发布商讯点击事件
 */
- (void)writeMessageButtonEvent
{

    //本句是用来让tableView在滚动情况下立即使视图停止滚动的。否则在tableView滚动时，按下发布商讯按钮，_drawerView会跟着向上滚动，导致视图变形
    [self.tableView setContentOffset:self.tableView.contentOffset animated:false];
    
    // 如果是关，则开，反之亦然
    if (_drawerView.isOpen == NO)
    {
        _drawerView.hidden = NO;
        [_drawerView openNavBarDrawer];
        
        self.tableView.scrollEnabled = NO;
        
        if (self.tableView.tableHeaderView != nil) {
            
            [self.view insertSubview:_drawerView aboveSubview:self.tableView.tableHeaderView];
        }
        
    }
    else
    {
        [_drawerView closeNavBarDrawer];
        
        [self recoverViewStatus];
    }
    
}

/*!
 @abstract 导航栏button点击事件
 */
- (void)buttonEvent:(id)sender
{
    //the controller we want to present as a popover
    CircleInPopoverViewController *controller = [[CircleInPopoverViewController alloc] init];
    controller.delegate = self;
    controller.circleId = _currentCircleId;
    _popover = [[FPPopoverController alloc] initWithViewController:controller];
    _popover.delegate = self;
    _popover.border = NO;
    _popover.tint = FPPopoverWhiteTint;
    _popover.arrowDirection = FPPopoverNoArrow;
    _popover.contentSize = CGSizeMake(170, 170);
    
    //sender is the UIButton view
    [_popover presentPopoverFromPoint:CGPointMake(160.0f, 15.0f)];
}

- (void)announcementViewEvent:(id)sender
{
    AnnouncementViewController *announcementVC = [[AnnouncementViewController alloc] initWithUrl:_announcementUrl];
    announcementVC.title = _announcementTitle;
    announcementVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:announcementVC animated:YES];
}

- (void)deleteButtonEvent:(id)sender
{
    UIButton *deleteButton = (UIButton *)sender;
    
    //将用户点击删除的公告放入数据库中
    //然后再更新公告的数组datasource
    DBKit *dbkit = [DBKit sharedDBKit];
    Announcement *announcement = [Announcement new];
    announcement.announcementId = deleteButton.tag;
    [dbkit save:announcement];
    
    //在数据源中去除被用户点击的公告
    for (NSDictionary *tmpAnnouncement in _announcementArray) {
        
        if ([tmpAnnouncement[@"id"] integerValue] == deleteButton.tag) {
            
            [_announcementArray removeObject:tmpAnnouncement];
            break;
        }
    }
    
    //当数据源为空的时候，那么就停止计时器，同时隐藏headerview
    if (_announcementArray.count == 0) {
        
        //停止定时器
        [_timer invalidate];
        _times = 0;
        
        [self hideAnnoucementView];
        
    }
    
    else
    {
        //由于在定时器方法中，执行一次showAnnoucementView后，会对_times递增操作，而此时用户点击删除后，数据源索引就会发生改变
        //所以_times-1才为此时应该显示的公告信息索引
        _times-=1;

        [self showAnnoucementView];
    }
}

#pragma mark - FPPopoverController Delegate
- (void)popoverControllerDidDismissPopover:(FPPopoverController *)popoverController
{
    _imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_001@2x" ofType:@"png"]];
}

- (void)popoverControllerDidPresentPopover:(FPPopoverController *)popoverController
{
    _imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_icon_002@2x" ofType:@"png"]];
}


#pragma mark - DynamicOperateDelegate

//
- (void)dynamic:(NSDictionary *)dynamic operate:(int)flag
{
    if (flag == 3) {
        [_messageArray removeObject:dynamic];
        [self.tableView reloadData];
    }
    else if (flag == 2) {
        for (int i = 0; i < _messageArray.count; i++) {
            
            NSDictionary* d = [_messageArray objectAtIndex:i];
            
            if ([d[@"id"] integerValue] == [dynamic[@"id"] integerValue]) {
                
                [_messageArray replaceObjectAtIndex:i withObject:dynamic];
                [self.tableView reloadData];
                break;
            }
        }
    }
}

#pragma mark - ACNavBarDrawerDelegate

- (void)navPlusBtnPressed:(UIButton *)sender
{
    
    [self recoverViewStatus];
}

-(void)theBtnPressed:(UIButton *)theBtn
{
    switch (theBtn.tag)
    {
            //发图文
        case 0:
        {
            MoodFormViewController* moodFormViewController = [[MoodFormViewController alloc] init];
            moodFormViewController.title = _L(@"vc_title_034");
            
            UINavigationController* moodNavigationController = [[UINavigationController alloc] initWithRootViewController:moodFormViewController];
            
            [Helper navigationControllerCommonStyle:moodNavigationController];
            [self.navigationController presentModalViewController:moodNavigationController animated:true];
        }
            break;
            
            //逛一逛
        case 1:
        {
            //检查此切片逛一逛功能是否开通
            [self shoppingEnableRequest];

        }
            break;
        default:
            break;
    }
    
    [self recoverViewStatus];
    
}

-(void)theBGMaskTapped
{

    [self recoverViewStatus];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self circleMessageRequestWithCheckId:nil];
    }
    
    //上拉加载更多
    else {
        
        //获取此时_messageArray中最后一条记录的id
        NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];

        [self circleMessageRequestWithCheckId:checkId];
    }
}

@end
